package com.skypan.myapplication.nfc;

import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;


import com.google.gson.Gson;
import com.skypan.myapplication.LocalDataApplication;
import com.skypan.myapplication.R;
import com.skypan.myapplication.bean.LoginR;
import com.skypan.myapplication.bean.ReadR;
import com.skypan.myapplication.bean.WriteR;
import com.skypan.myapplication.http.LoginCallback;
import com.skypan.myapplication.http.WriteCallback;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;

import okhttp3.Call;

public class ReadTextActivity extends BaseNfcActivity {

    Calendar calendar = Calendar.getInstance();
    String year = String.valueOf(calendar.get(Calendar.YEAR));
    String month = String.valueOf(calendar.get(Calendar.MONTH)+1);
    String day = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
    String hour = String.valueOf(calendar.get(Calendar.HOUR_OF_DAY));
    String minute = String.valueOf(calendar.get(Calendar.MINUTE));
    String second = String.valueOf(calendar.get(Calendar.SECOND));
    String time = year + "-" + month + "-" + day + " "+ hour + ":" + minute + ":" + second;

    private TextView mNfcTagText;
    private TextView mNfcProductText;
    private TextView mNfcTransferText;
    private String mTagText;
    private String mProductText;
    private String mTransferText;
    private String url = "http://39.105.165.31:8080/event/add";
    private ReadR event;
    private ReadR.Object data;
    LoginR localuser = LocalDataApplication.getInstance().getLocalResponse();
    String user_Id = localuser.data.userId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_read_text);
        mNfcTagText = (TextView) findViewById(R.id.nfc_tag_text);
        mNfcProductText = (TextView) findViewById(R.id.nfc_product_text);
        mNfcTransferText = (TextView) findViewById(R.id.nfc_transport_text);
        event = new ReadR();
        data = new ReadR.Object();
    }

    @Override
    public void onNewIntent(Intent intent) {
        //1.获取Tag对象
        super.onNewIntent(intent);
        Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        byte[] tagbytes = detectedTag.getId();    //NFC的ID转16进制字符串
        String mTagId = bytesToHexString(tagbytes);

        //2.获取Ndef的实例
        Ndef ndef = Ndef.get(detectedTag);
        mTagText = "标签类型 : " + ndef.getType() + "\n标签容量 : " + ndef.getMaxSize() + "bytes" + "\n标签id : " + mTagId;
        readNfcTag(intent);
        mNfcTagText.setText(mTagText);
        mNfcProductText.setText(mProductText);
        mNfcTransferText.setText(mTransferText);
        initEvent(mTagId);

    }

    /**
     * 读取NFC标签文本数据
     */
    private void readNfcTag(Intent intent) {
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
                    NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage msgs[] = null;
            int contentSize = 0;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                    contentSize += msgs[i].toByteArray().length;
                }
            }
            try {
                if (msgs != null) {
                    NdefRecord record = msgs[0].getRecords()[0];
                    String textRecord = parseTextRecord(record);
                    mTagText += "\n数据容量：" + contentSize + " bytes";
                    mProductText = textRecord.substring(0, textRecord.indexOf("物流公司ID："));
                    mTransferText = textRecord.substring(textRecord.indexOf("物流公司ID："));

                }
            } catch (Exception e) {
            }
        }
    }

    /**
     * 解析NDEF文本数据，从第三个字节开始，后面的文本数据
     *
     * @param ndefRecord
     * @return
     */
    public static String parseTextRecord(NdefRecord ndefRecord) {
        /**
         * 判断数据是否为NDEF格式
         */
        //判断TNF
        if (ndefRecord.getTnf() != NdefRecord.TNF_WELL_KNOWN) {
            return null;
        }
        //判断可变的长度的类型
        if (!Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
            return null;
        }
        try {
            //获得字节数组，然后进行分析
            byte[] payload = ndefRecord.getPayload();
            //下面开始NDEF文本数据第一个字节，状态字节
            //判断文本是基于UTF-8还是UTF-16的，取第一个字节"位与"上16进制的80，16进制的80也就是最高位是1，
            //其他位都是0，所以进行"位与"运算后就会保留最高位
            String textEncoding = ((payload[0] & 0x80) == 0) ? "UTF-8" : "UTF-16";
            //3f最高两位是0，第六位是1，所以进行"位与"运算后获得第六位
            int languageCodeLength = payload[0] & 0x3f;
            //下面开始NDEF文本数据第二个字节，语言编码
            //获得语言编码
            String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
            //下面开始NDEF文本数据后面的字节，解析出文本
            String textRecord = new String(payload, languageCodeLength + 1,
                    payload.length - languageCodeLength - 1, textEncoding);
            return textRecord;
        } catch (Exception e) {
            throw new IllegalArgumentException();
        }
    }


    //数据对象处理，显示，上传，
    public void initEvent(String mTagId){
        event.setCode(0);
        event.setMsg("success");
        data.setTagId(mTagId);
        data.setUserId(user_Id);
        data.setEventDate(time);
        data.setEventLocation("zz");
        data.setEventStatus("1");
        event.setData(data);

        postEvent(event,url);
    }

    public void postEvent(ReadR event, String url) {

        OkHttpUtils
                .post()//
                .url(url)//
                .addParams("tagId", event.data.tagId)//
                .addParams("userId", event.data.userId)//
                .addParams("eventDate",event.data.eventDate)//
                .addParams("eventLocation", "zz")//
                .addParams("eventStatus",event.data.eventStatus)//

                .build()//
                .execute(new WriteCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(ReadTextActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
                    }


                    public void onResponse(WriteR response, int id) {
                            Toast.makeText(ReadTextActivity.this,response.getMsg(),Toast.LENGTH_SHORT).show();
                    }
                });

    }

    private String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();

        if (src == null || src.length <= 0) {
            return null;
        }
        char[] buffer = new char[2];
        for (int i = 0; i < src.length; i++) {
            buffer[0] = Character.toUpperCase(Character.forDigit(
                    (src[i] >>> 4) & 0x0F, 16));
            buffer[1] = Character.toUpperCase(Character.forDigit(src[i] & 0x0F,
                    16));
            System.out.println(buffer);
            stringBuilder.append(buffer);
        }
        return stringBuilder.toString();
    }


}
